import { useState, useEffect } from 'react';
import { Spin } from 'antd';
import type { ProColumns } from '@ant-design/pro-table';
import { crud } from './api';
import BasicForm from './form';
import { getTenant, getTenantOptions } from '../Tenant/api';
import { useModel } from 'umi';
import BasicFormTable from '@/components/BasicFormTable';
import { ADMIN_ROLE_NAME } from '@/constants';

export default () => {
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};

  const [tenantOptions, setTenantOptions] = useState<OptionEntity[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [tenantId, setTenantId] = useState<string>();
  const [tenant, setTenant] = useState<TenantEntity>();

  async function initTenantOptions() {
    try {
      const options = await getTenantOptions();
      setTenantOptions(options);
    } catch (error) {
    } finally {
      setLoading(false);
    }
  }

  const initTenant = async (id: string) => {
    const newTenant = await getTenant(id);
    setTenant(newTenant);
  };

  const normalize = (data: AnyFields) => ({
    ...data,
    allow_nodes: data.nodes.join(','),
    tenant_id: tenantId,
  });

  useEffect(() => {
    initTenantOptions();
  }, []);

  useEffect(() => {
    if (currentUser?.currentGroup) {
      setTenantId(currentUser.currentGroup);
    }
  }, [currentUser?.currentGroup]);

  useEffect(() => {
    if (tenantId) {
      initTenant(tenantId);
    }
  }, [tenantId]);

  if (loading) return <Spin spinning={true} />;

  const columns: ProColumns<RoleEntity>[] = [
    {
      title: '名称',
      dataIndex: 'name',
      hideInSearch: true,
    },
    {
      title: '节点',
      dataIndex: 'allow_nodes',
      hideInSearch: true,
    },
    {
      title: '最大CPU(核)',
      dataIndex: 'max_cpu',
      hideInSearch: true,
    },
    {
      title: '最大内存(G)',
      dataIndex: 'max_memory',
      hideInSearch: true,
    },
    {
      title: '最大硬盘(G)',
      dataIndex: 'max_disk',
      hideInSearch: true,
    },
    {
      title: '租户',
      dataIndex: 'tenant_id',
      hideInTable: true,
      valueType: 'select',
      fieldProps: {
        allowClear: false,
        options: tenantOptions,
        onChange: (value: string) => setTenantId(value),
      },
      initialValue: tenantId,
    },
  ];

  return (
    <BasicFormTable<RoleEntity>
      title={'角色'}
      columns={columns}
      search={{
        optionRender: false,
        collapsed: false,
        labelWidth: 'auto',
      }}
      params={{
        tenant_id: tenantId,
      }}
      postData={(data) =>
        data.map((item) => ({
          ...item,
          nodes: item.allow_nodes.split(',') || [],
        }))
      }
      crud={{
        ...crud,
        add: (data) => crud.add(normalize(data)),
        update: (data) => crud.update(normalize(data)),
      }}
      addForm={<BasicForm tenant={tenant} />}
      updateForm={<BasicForm tenant={tenant} />}
      renderActions={(actions, record) => {
        if (record.name === ADMIN_ROLE_NAME) return actions.slice(0, 1);
        return actions;
      }}
    />
  );
};
